﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Chemistry.Models;
using Newtonsoft.Json;

namespace Chemistry.Tools
{
    /// <summary>
    /// 服务器日志
    /// <remarks>
    /// 通过udp发送日志
    /// 58.213.157.99:34566
    /// </remarks>
    /// </summary>
    public class ServerLogTool
    {
        private static IPEndPoint _ipEndPoint;
        static ServerLogTool ()
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var settings = config.AppSettings.Settings;
                var item = settings["LOGADDRESS"];
                if (item != null)
                {
                    string ip = item.Value;
                    IPAddress address = IPAddress.Parse(ip);
                    _ipEndPoint = new IPEndPoint(address, 34566);
                }
            }
            catch (Exception ex)
            {
                IPAddress address = IPAddress.Parse("58.213.157.99");
                _ipEndPoint = new IPEndPoint(address, 34566);
                LogTool.WriteErrorLog(ex);
            }
             
        }

        public static void UploadLog(string content,EventType type)
        {
            try
            {
                UdpClient udp = new UdpClient();
                ClientTracer ct = new ClientTracer()
                {
                    clientId = 0,
                    clientName = Global.ClientName,
                    collection = "exam.chemistry",
                    content = content,
                    eventType = type,
                    serial = Global.LogSerial++
                };
                string c = JsonConvert.SerializeObject(ct);
                byte[] data = Encoding.UTF8.GetBytes(c);
                udp.Send(data, data.Length, _ipEndPoint);
            }
            catch (Exception ex)
            {
                LogTool.WriteErrorLog(ex);
            }
            
        }
    }
}
